﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using CNVP.Framework.Utils;

namespace CNVP.Cache
{
    public abstract class FileCacheBase
    {
        #region 属性定义
        /// <summary>
        /// 文件统一的编码格式
        /// </summary>
        private System.Text.Encoding _FileEncoding = System.Text.Encoding.UTF8;
        /// <summary>
        /// 文件统一的编码格式
        /// </summary>
        public System.Text.Encoding FileEncoding
        {
            get { return _FileEncoding; }
            set { _FileEncoding = value; }
        }

        /// <summary>
        /// Cache文件存放基本目录
        /// </summary>
        private string _FileSavePath = @"C:\CacheFiles\";
        /// <summary>
        /// Cache文件存放基本目录
        /// </summary>
        public string FileSavePath
        {
            get { return _FileSavePath; }
            set { _FileSavePath = value; }
        }

        /// <summary>
        /// 文件扩展名
        /// </summary>
        private string _FileExt = ".cache";
        /// <summary>
        /// Cache文件扩展名
        /// </summary>
        public string FileExt
        {
            set { _FileExt = value; }
            get { return _FileExt; }
        }

        /// <summary>
        /// 文件缓存的时间 单位分
        /// </summary>
        private int _FileCacheMiniutes = 2;
        /// <summary>
        /// 文件缓存的时间 单位分
        /// </summary>
        public int FileCacheMiniutes
        {
            get { return _FileCacheMiniutes; }
            set { _FileCacheMiniutes = value; }
        }
        #endregion

        /// <summary>
        /// 检查文件是否存在
        /// </summary>
        /// <param name="p_FileName">文件名，不带路径，不带扩展名</param>
        /// <returns></returns>
        protected bool ExistFile(string p_FileName)
        {
            bool resultValue = false;
            try
            {
                string strFileName = _FileSavePath + p_FileName + _FileExt;
                if (File.Exists(strFileName))
                {
                    //文件是否过期
                    DateTime tmFile = File.GetLastWriteTime(strFileName);
                    DateTime tmNow = DateTime.Now;
                    TimeSpan ts = tmNow - tmFile;
                    if (ts.TotalMinutes < _FileCacheMiniutes)
                    {
                        resultValue = true;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            return resultValue;
        }

        /// <summary>
        /// 读文本文件
        /// </summary>
        /// <param name="p_FileName">文件名，不带路径，不带扩展名</param>
        /// <param name="p_Content">返回用于存放内容的变量</param>
        /// <returns></returns>
        protected bool ReadFile(string p_FileName, ref string p_Content)
        {
            bool resultValue = false;
            if (!this.ExistFile(p_FileName))
            {
                return resultValue;
            }
            try
            {
                if (!Directory.Exists(_FileSavePath))
                {
                    Directory.CreateDirectory(_FileSavePath);
                }

                System.IO.StreamReader sr = new StreamReader(_FileSavePath + p_FileName + _FileExt, _FileEncoding);
                p_Content = sr.ReadToEnd();
                sr.Close();
                resultValue = true;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            return resultValue;
        }
        /// <summary>
        /// 保存文本文件
        /// </summary>
        /// <param name="p_FileName">文件名，不带路径，不带扩展名</param>
        /// <param name="p_Content">内容</param>
        /// <returns></returns>
        protected bool SaveFile(string p_FileName, string p_Content)
        {
            bool resultValue = false;
            try
            {
                if (!Directory.Exists(_FileSavePath))
                {
                    Directory.CreateDirectory(_FileSavePath);
                }

                System.IO.StreamWriter sw = new StreamWriter(_FileSavePath + p_FileName + _FileExt, false, _FileEncoding);
                sw.Write(p_Content);
                sw.Close();
                resultValue = true;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            return resultValue;
        }
        /// <summary>
        /// 根据域名取得无扩展名的文件名
        /// </summary>
        /// <param name="p_Url"></param>
        /// <param name="p_Domain">域名</param>
        /// <returns></returns>
        protected string GetFileNameNoExt(string p_Url, string p_Domain)
        {
            string fileNameNoExt = p_Url.Replace("http://" + p_Domain + "/", "");
            fileNameNoExt = FormatFilename(fileNameNoExt);
            //处理未带文件名的情况
            if (fileNameNoExt == "")
            {
                fileNameNoExt = "default";
            }
            return fileNameNoExt;
        }
        /// <summary>
        /// 取扩展名
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        protected string GetExtension(string fileName)
        {
            try
            {
                int startPos = fileName.LastIndexOf(".");
                string ext = fileName.Substring(startPos, fileName.Length - startPos);
                return ext.ToLower();
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }
        /// <summary>
        /// 取有扩展名的文件名
        /// </summary>
        /// <param name="p_Url"></param>
        /// <returns></returns>
        protected string GetFileName(string p_Url)
        {
            try
            {
                int startPos = p_Url.LastIndexOf("/") + 1;
                string tmpFileName = p_Url.Substring(startPos, p_Url.Length - startPos);
                return tmpFileName;
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }
        /// <summary>
        /// 取得URL的页面内容
        /// </summary>
        /// <param name="p_PageUrl">URL地址要完整的</param>
        /// <returns></returns>
        protected string GetUrlResponse(string p_PageUrl)
        {
            //给URL加入ServerGet的参数，以防止重复循环
            if (p_PageUrl.IndexOf("?") > 0)
            {
                p_PageUrl += "&serverget=1";
            }
            else
            {
                p_PageUrl += "?serverget=1";
            }
            WebRequest webrequest = WebRequest.Create(p_PageUrl);
            string strContent = "";
            try
            {
                WebResponse webresponse = webrequest.GetResponse();
                Stream stream = webresponse.GetResponseStream();
                StreamReader sr = new StreamReader(stream, _FileEncoding);

                strContent = sr.ReadToEnd();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            return strContent;
        }
        #region 格式化文件名,替换非法字符
        /// <summary>
        /// 格式化文件名,替换非法字符
        /// </summary>
        /// <param name="p_fileName">需要格式化的文件名</param>
        /// <returns>格式化后的文件名</returns>
        protected static string FormatFilename(string p_fileName)
        {
            p_fileName = p_fileName.Replace("\\", "_");
            p_fileName = p_fileName.Replace("/", "_");
            p_fileName = p_fileName.Replace(":", "_");
            p_fileName = p_fileName.Replace("*", "_");
            p_fileName = p_fileName.Replace("?", "_");
            p_fileName = p_fileName.Replace("\"", "_");
            p_fileName = p_fileName.Replace("<", "_");
            p_fileName = p_fileName.Replace(">", "_");
            p_fileName = p_fileName.Replace("|", "_");
            p_fileName = p_fileName.Replace("+", "_");
            return EncryptUtils.MD5(p_fileName).ToLower();
            //return p_fileName.ToLower();
        }
        #endregion
    }
}